package com.atguigu.tingshu.dispatch.job;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.result.Result;

import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DispatchJobHandler {
	@Autowired
	private SearchFeignClient searchFeignClient;
	@Autowired
	private XxlJobLogMapper xxlJobLogMapper;
	@Autowired
	private UserInfoFeignClient userInfoFeignClient;

	@XxlJob("updateLatelyAlbumRankingHandler")
	public void updateLatelyAlbumRankingHandler(){
		log.info("DispatchJobHandler.updateLatelyAlbumRankingHandler");
		long startTime = System.currentTimeMillis();
		Result<Void> result = searchFeignClient.updateLatelyAlbumRanking();
		long endTime = System.currentTimeMillis();
		long jobId = XxlJobHelper.getJobId();
		XxlJobLog xxlJobLog = new XxlJobLog();
		xxlJobLog.setJobId(jobId);
		if(result.getCode().equals(200)){
			xxlJobLog.setStatus(1);
		}else {
			xxlJobLog.setStatus(0);
			xxlJobLog.setError(result.getMessage());
		}
		xxlJobLog.setTimes((int)(endTime-startTime));
		xxlJobLogMapper.insert(xxlJobLog);
		log.info("更新 Redis 专辑排名成功 xxlJobLog: {}", JSON.toJSONString(xxlJobLog));
	}


	@XxlJob("updateVipExpireHandler")
	public void updateVipExpireHandler(){
		log.info("DispatchJobHandler.updateVipExpireHandler");
		long startTime = System.currentTimeMillis();
		Result<Void> result = userInfoFeignClient.updateVipExpireHandler();
		long endTime = System.currentTimeMillis();
		long jobId = XxlJobHelper.getJobId();
		XxlJobLog xxlJobLog = new XxlJobLog();
		xxlJobLog.setJobId(jobId);
		if(result.getCode().equals(200)){
			xxlJobLog.setStatus(1);
		}else {
			xxlJobLog.setStatus(0);
			xxlJobLog.setError(result.getMessage());
		}
		xxlJobLog.setTimes((int)(endTime-startTime));
		xxlJobLogMapper.insert(xxlJobLog);
		log.info("更新用户 Vip 状态成功 xxlJobLog: {}", JSON.toJSONString(xxlJobLog));
	}

}